import struct
import numpy as np
import matplotlib.pyplot as plt


def read_images(file_path):
    with open(file_path, 'rb') as file:
        # 读取魔数和图像信息
        magic_number, num_images, num_rows, num_columns = struct.unpack('>IIII', file.read(16))
        print(f"Magic Number: {magic_number}, Number of Images: {num_images}, Rows: {num_rows}, Columns: {num_columns}")

        # 读取所有图像
        images = np.fromfile(file, dtype=np.uint8).reshape(num_images, num_rows, num_columns)

    return images


# 使用示例
file_path = 'S:\托马斯办公\云资料-tms\AS\pythonProject\tms_202\MNIST\raw\train-images-idx3-ubyte'
images = read_images(file_path)
print(f"First Image Shape: {images[0].shape}")

# 显示第一张图像
plt.imshow(images[0], cmap='gray')
plt.show()
